package su.theravada.jpalireader.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class ZipUtil 
{
	public static String LoadContentFile(String strFileName,String strArchiveName)
	{
		String strFileContent="";
		ZipFile objCanonZip=null;
		try
		{				
			objCanonZip = new ZipFile(System.getProperty("user.dir")+"/"+strArchiveName);
			ZipEntry objFile=objCanonZip.getEntry(strFileName.toLowerCase()+".htm");
						
			//this is required to work on linux that is case-sensitive!
			if(objFile==null)
				objFile=objCanonZip.getEntry(strFileName.toUpperCase()+".htm");
			
			InputStream stream=objCanonZip.getInputStream(objFile);			
			
			if(stream!=null)
				strFileContent=new java.util.Scanner(stream,"UTF-8").useDelimiter("\\A").next();
		}
		catch(Exception ex1)
		{ 
			ex1.printStackTrace();
		}				
		finally
		{
			try 
			{
				objCanonZip.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return strFileContent;
	}	
	
	public static String LoadContentFile(String strFileName,String strArchiveName,boolean showBold,boolean showFont)
	{
		String strFileContent=ZipUtil.LoadContentFile(strFileName, strArchiveName);
		
		strFileContent=strFileContent.replace("</HEAD>", "<link rel='stylesheet' type='text/css' href='style.css'></HEAD>");
		strFileContent=strFileContent.replace("</head>", "<link rel='stylesheet' type='text/css' href='style.css'></head>");

		if(!showBold)
		{
			Matcher objBoldMatcher=Pattern.compile("<(/)?b[^>]*>",Pattern.CASE_INSENSITIVE).matcher(strFileContent);
			strFileContent=objBoldMatcher.replaceAll("");
		}
		
		if(!showFont)
		{
			Matcher objFontMatcher=Pattern.compile("<(/)?span[^>]*>",Pattern.CASE_INSENSITIVE).matcher(strFileContent);
			strFileContent=objFontMatcher.replaceAll("");
		}
		
		return strFileContent;
	}
	
}
